// vim: set et sw=4 ts=4 sts=4 fdm=marker ff=unix fenc=utf8 nobomb:
/**
 * popup.js
 *
 * @author mingcheng<i.feelinglucky#gmail.com>
 * @date   2009-11-26
 * @link   http://www.gracecode.com/
 */
~function() {
    var Util = YAHOO.util, Dom = Util.Dom, Event = Util.Event, Lang = YAHOO.lang;
    var backgroundPage = chrome.extension.getBackgroundPage(), 
        bgElements = backgroundPage.Elements, bgServer = backgroundPage.Server
        bgTweets = backgroundPage.Tweets, bgTwitter = backgroundPage.Twitter;
    var requesting = false, in_user = '', in_status = '';

    ~function() {
        var views = [
            Helper.Conf.Get('show_tabs_home',      'yes'), 
            Helper.Conf.Get('show_tabs_mention',   'yes'),
            Helper.Conf.Get('show_tabs_direct',    'yes'), 
            Helper.Conf.Get('show_tabs_favourite', 'yes')
        ];
        var li =  Dom.get('channel').getElementsByTagName('li');
        for(var i = 0, len = li.length; i < len; i++) {
            if (views[i] != 'yes') {
                Dom.setStyle(li[i], 'display', 'none');
            }
        }
    }();

    /*
    if (Helper.Conf.Get('use_console', 'yes') == 'yes') {
        window.console = UI.HTMLConsole;
    } else {
        Dom.addClass('metrist:console', 'hidden');
        Dom.addClass('Console', 'hidden');
    }
    // */

    var Tweets = (function() {
        var tryTimes = 0, latestDelId;
        return {
            destroy: function(id) {
                latestDelId = id;
                bgTwitter.destroy(id, {
                    onSuccess: function(o) {
                        requesting = false;
                        //var results = JSON.parse(o.responseText);
                        bgTweets.removeItem(id);
                        var el = Dom.get(id), attributes = {
                            opacity: {from: 1, to: 0}
                        }; 
                        var anim = new Util.Anim(el, attributes, .8); 
                        anim.onComplete.subscribe(function() {
                            Dom.setStyle(el, 'display', 'none');
                            UI.Notice.show('Tweets has been deleted');
                            console.info('Tweets['+ id +'] has been deleted');
                        });
                        backgroundPage.Sync();
                        tryTimes = 0;
                        anim.animate();
                    },

                    onError: function(o) {
                        if (tryTimes >= 2 && latestDelId == id) {
                            //bgTweets.removeItem('friends', id);
                            //Dom.setStyle(id, 'display', 'none');
                        }
                        UI.Notice.show('Ops, Tweets delete error!');
                        console.error('Tweets['+ id +'] delete error');
                        requesting = false; tryTimes++;
                    }
                });
            },

            update: function() {
                UI.Loading.showMini();
                backgroundPage.Twitter.update({
                    "status": UI.InputArea.getValue(),
                    "in_user": in_user,
                    "in_status": in_status
                }, {
                    onSuccess: function(o) {
                        UI.InputArea.setValue('', true);
                        UI.Loading.hideMini(function() {
                            bgTweets.addToList('timeline', [JSON.parse(o.responseText)]);
                            backgroundPage.Sync();
                            Dom.get('metrist:friends').innerHTML = bgElements.getHTML('friends');
                            console.info('Update successful');
                            UI.Notice.show('Update successful');
                        });
                    },
                    onError: function() {
                        UI.Loading.hide();
                        UI.Notice.show('Update tweets error');
                        console.info('Update tweets error')
                    }
                });
            },

            isRequesting: function() {
                return bgServer.status().requesting;
            },

            clearUnreadNum: function() {
                Lang.later(1000, window, function() {
                    bgTweets.clearUnreadNum();
                    Helper.Func.setBadgeText('');
                });
            }
        };
    })();


    var TweetsTextAreaEl = Dom.get('form:input'), TweetsUpdateBtnEl = Dom.get('submit'),
        TweetsUpdateFormEl = Dom.get('metrist:form');

    Event.on(TweetsUpdateFormEl, 'submit', function(e) {
        Event.stopEvent(e);
        return false;
    });

    Event.on(TweetsUpdateBtnEl, 'click', function(e) {
        var e = Event.getEvent(e), tweets_text = UI.InputArea.getValue();
        Event.stopEvent(e);
        Helper.Status.Set('last_input', tweets_text);
        if (tweets_text.length) Tweets.update();
        /*
        if (UI.InputArea.check()) {
            Tweets.update();
        }
        */
    });

    Event.on(TweetsTextAreaEl, 'keydown', function(e) {
        var e = Event.getEvent(e), tweets_text = UI.InputArea.getValue();
        Helper.Status.Set('last_input', tweets_text);
        if (Event.getCharCode(e) == 13 /* && e.ctrlKey */) {
            Event.stopEvent(e);
            if (tweets_text.length) Tweets.update();
        }
    });

    // 切换时候的代码
    UI.Channel.setSwitchToCall(function() {
        var current = UI.Channel.getCurrentIdx(), container = UI.Channel.containers[current];
        var loaded = Dom.getAttribute(container, 'loaded'),
            ref = Dom.getAttribute(container, 'ref');

        Helper.Status.Set('last_index', current);
        ///*
        if (Helper.Conf.Get('use_console', 'yes') == 'yes') {
            if (container.getAttribute('id') == 'metrist:console') {
                UI.HTMLConsole.refresh();
            }
        }
        // */
        if (loaded != 'loaded' && ref) {
            Dom.setAttribute(container, 'loaded', 'loaded');
            container.innerHTML = bgElements.getHTML(ref);
        }
    });

    //var defaultIdx = parseInt(Helper.Status.Get('last_index', 0), 10) || 0;
    var defaultIdx = 0;
    Dom.setStyle('content', 'visibility', 'hidden');
    UI.Loading.show(function() {
        var foo = Lang.later(50, window, function() {
            if (!Tweets.isRequesting()) {
                foo.cancel();
                UI.Loading.hide(function() {
                    Dom.setStyle('content', 'visibility', '');
                    bgTweets.clearUnreadNum(); // clear unread

                    // 及时更新输入框状态以及数据
                    Lang.later(500, window, function() {
                        UI.InputArea.check();
                        var inputValue = UI.InputArea.getValue();
                        if (!inputValue || inputValue.indexOf('@'+in_user) == -1) {
                            in_user = ''; in_status = '';
                        }

                        Helper.Status.Set('last_input', inputValue);
                    }, null, true); 

                    // 最后获取时间
                    Dom.get('refresh').setAttribute('title', 'Request ' + 
                        Helper.Func.relativeTime(Helper.Status.Get('last_request_tweets', '')).toLowerCase());

                    UI.Channel.switchTo(defaultIdx, false); // Hallelujah!!!
                }, false);
            }
        }, null, true);
    });

    // 清除未读信息
    Helper.Func.setBadgeText('');
    bgTweets.clearUnreadNum();
    //backgroundPage.Sync();
    UI.InputArea.setValue(Helper.Status.Get('last_input', ''));

    // 刷新事件
    var foo = null, refreshEvent = function(e) {
        if (!Lang.isUndefined(e)) { Event.stopEvent(e); }
        UI.Loading.show(function() {
            if (foo){ foo.cancel(); };
            bgServer.restart();
            foo = Lang.later(50, window, function() {
                if (!Tweets.isRequesting()) {
                    foo.cancel();
                    UI.Loading.hide(function(){
                        //Dom.get('friends').appendChild(Elements.get('friends'));
                        Dom.get('refresh').setAttribute('title', 'Request ' + 
                            Helper.Func.relativeTime(Helper.Status.Get('last_request_tweets', '')).toLowerCase());
                    });
                };
            }, null, true);
        });
    };
    Event.on('refresh', 'click', refreshEvent);

    // 点击弹出配置页
    Event.on('config', 'click', function(e) {
        Event.stopEvent(e);
        chrome.tabs.create({url: 'options.html'});
    });

    // 界面点击事件
    Event.on('content', 'click', function(e) {
        var target = Event.getTarget(e);
        if (target.nodeName.toLowerCase() == 'a') {
            Event.stopEvent(e);
            var act = (Dom.getAttribute(target, 'act') || '').toLowerCase();
            if (act) {
                switch (act) {
                    case 'reply': case 'direct': 
                        var ancestor = Dom.getAncestorByTagName(target, 'li');
                        if (ancestor) {
                            var isDirect = !!Dom.hasClass(ancestor, 'direct'),
                                prefix = isDirect ? 'd ' : '@',
                                screen_name = Dom.getAttribute(ancestor, 'screen_name'),
                                value = prefix + screen_name + ' ';
                            var inputAreaEmpty = !!UI.InputArea.getValue();

                            if (!isDirect && inputAreaEmpty) {
                                value = UI.InputArea.getValue() + ' ' + value;
                            }
                            in_user = screen_name;
                            in_status = Dom.getAttribute(ancestor, 'id');
                            UI.InputArea.setValue(value, true, false);
                            UI.InputArea.check();
                            UI.InputArea.focus();
                        }
                    break;

                    case 'retweet':
                        var ancestor = Dom.getAncestorByTagName(target, 'li');
                        if (ancestor) {
                            var screen_name = Dom.getAttribute(ancestor, 'screen_name')
                            var value = 'RT @' + screen_name + ': '
                                    + Dom.getAttribute(ancestor, 'tweets_text');
                            UI.InputArea.setValue(value, true, false);
                            UI.InputArea.check();
                            UI.InputArea.focus();
                        }
                    break;

                    case 'delete':
                        var ancestor = Dom.getAncestorByTagName(target, 'li');
                        if (ancestor) {
                            var id = Dom.getAttribute(ancestor, 'id');
                            if (id && !requesting) {
                                requesting = true;
                                Tweets.destroy(id);
                            }
                        }
                    break;
                    default: return;
                }
             } else {
                var href = Dom.getAttribute(target, 'href') || '';
                if (/^(http|https):\/\//.test(href)) {
                    // AutoExpandURL
                    var shortHosts = Helper.Conf.Get('autoexpand_short_url_host', 'bit.ly').split(',');
                    var short = !!(shortHosts.indexOf(target.hostname) != -1);
                    if (Helper.Conf.Get('autoexpand_short_url', 'no') == 'yes' && short) {
                        Helper.AutoExpandURL(href, {
                            onSuccess: function(url) {
                                console.log('auto expanded url from: ' + href + ' to: ' + url);
                                chrome.tabs.create({url: url});
                            },

                            onError: function() {
                                console.log('none of auto expanded url, directly jump');
                                chrome.tabs.create({url: href});
                            }, timeout: 3000
                        });
                    } else {
                        chrome.tabs.create({url: href});
                    }
                }
             }
        }
    });

    // set visual fontsize
    Dom.addClass('page', Helper.Conf.Get('fontszie', 'normal'));
}();
